package com.gyg.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 自定义redisTemplate
 * 解决实现序列化
 *
 * @author YunGang.Guo
 * @date 2021/12/27 14:45
 **/
@Configuration
public class RedisConfig {

    /**
     * 编写自己的redisTemplate
     *
     * @param factory
     * @return
     */
    @Bean("redisTemplate")
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        System.out.println("redisTemplate");
//      为了开发方便，一般都使用<String, Object>类型
        RedisTemplate<String, Object> template = new RedisTemplate();
//      连接工厂
        template.setConnectionFactory(factory);

//        序列化配置
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
//        value值的序列化采用FastJsonRedisSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
//        hash值的序列化采用FastJsonRedisSerializer的方式
        template.setHashValueSerializer(fastJsonRedisSerializer);

//        key的序列化采用StringRedisSerializer
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
//        hash的key的序列化采用StringRedisSerializer的方式
        template.setHashKeySerializer(stringRedisSerializer);

        return template;
    }
}
